package core;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import messages.Message;
import user.User;
import util.Pair;

public class MessageConsumer implements Runnable {
	
	public MessageConsumer() {
		new Thread(this, "MessageConsumer").start();
	}
	
	public void run() {
		while(true){
			try {					
				Pair<Message, User> pair = queue.take();
				Controller.getInstance().forward(pair.getFirst(), pair.getSecond());				
			} 
			catch (InterruptedException e) {			
				e.printStackTrace();
			}	
		}
	}

	
	public void putMessage(Message message, User user) {
		try {
			System.err.println("Received " + message + " from " + user.getLogin());
			this.queue.put(new Pair<Message, User>(message, user));
		} catch (InterruptedException e) {			
			e.printStackTrace();
		}
	}
	
	
	private BlockingQueue<Pair<Message, User>> queue = new LinkedBlockingQueue<Pair<Message, User>>();
}


